package com.mls.guardian.appst.chain.excutor;

import com.mls.guardian.appst.chain.TaskExecutor;
import com.mls.guardian.appst.chain.TaskInvoker;
import com.mls.guardian.appst.chain.TaskResult;
import com.mls.guardian.appst.shell.ShellScriptExecutorFuture;
import com.mls.guardian.common.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 2014-400 on 2015-10-26.
 */
public class RestartTomcatExcutor implements TaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(RestartTomcatExcutor.class);

    @Override
    public TaskResult exec(TaskInvoker invoker) {
        List<String> tomcatHomeList = invoker.getProject().getTomcatHomeList();
        TaskResult result = null;

        log.info("----开始restart tomcat----");
        for (String itemTomcatHome : tomcatHomeList) {
            log.info("----restart tomcat[{}]----", itemTomcatHome);
            String bashFilePath = System.getProperty("user.home") + File.separator + "guardianConfig" + File.separator + "guardian_" + System.currentTimeMillis() + ".sh";
            try {
                String startFolder = Paths.get(itemTomcatHome, "bin").toString();
                if (false == itemTomcatHome.substring(itemTomcatHome.length() - 1, itemTomcatHome.length()).equals(File.separator)) {
                    itemTomcatHome = itemTomcatHome + File.separator;
                }

                FileUtil.append(bashFilePath, "pid=$(ps -ef|grep tomcat |grep spring.profiles.active |grep " + itemTomcatHome + " |awk '{print $2}')");
                FileUtil.append(bashFilePath, "echo killing $pid");
                FileUtil.append(bashFilePath, "OLD_IFS=\"$IFS\"");
                FileUtil.append(bashFilePath, "IFS=\" \"");
                FileUtil.append(bashFilePath, "arr=($pid)");
                FileUtil.append(bashFilePath, "IFS=\"$OLD_IFS\"");
                FileUtil.append(bashFilePath, "for s in ${arr[@]}");
                FileUtil.append(bashFilePath, "do");
                FileUtil.append(bashFilePath, "echo killed $s");
                FileUtil.append(bashFilePath, "kill -9 $s");
                FileUtil.append(bashFilePath, "done");
                FileUtil.append(bashFilePath, "echo kill pid finished");
                FileUtil.append(bashFilePath, "cd " + startFolder);
                FileUtil.append(bashFilePath, "sh startup.sh");
                FileUtil.append(bashFilePath, "echo done");

                result = new ShellScriptExecutorFuture("sh " + bashFilePath).execute();

                //暂停一下
                int sleepSecond = invoker.getConfig().getRestartSleep();
                if (sleepSecond <= 0) {
                    sleepSecond = 10;
                }
                try {
                    Thread.sleep(sleepSecond * 1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //一旦报错,停止循环
                if (result.isSuc() == false) {
                    break;
                }
            } catch (Exception e) {
                result = new TaskResult();
                result.setSuc(false);
                result.setError(e.getMessage());

                e.printStackTrace();
            } finally {
                try {
                    Files.delete(Paths.get(bashFilePath));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                log.info("----结束restart tomcat[{}]----", itemTomcatHome);
            }

        }//end-for

        if (result == null) {
            result = new TaskResult();
            result.setSuc(true);
        }
        log.info("----结束restart tomcat[{}]----", result.isSuc());


        if (result.isSuc() == true) {
            return invoker.invoke();
        }

        return result;
    }
}